package com.cictec.middleware.gps.engine.position.handler;

import java.io.Serializable;

import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.exception.BusPositionHandlerException;
import com.cictec.middleware.gps.engine.position.BusPositionHandler;
import com.cictec.middleware.gps.engine.utils.MultiLogUtil;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.DeviateService;

/**
 * 偏线判断 存在线路上下行
 * 
 * @author zhou qi
 *
 */
@Component
public class BusPositionDeviateHandler implements BusPositionHandler {

	private Logger logger = LoggerFactory.getLogger(BusPositionStandbyHandler.class);
	
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private DeviateService deviateService;
	
	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionHandlerException {

		MultiLog log = MultiLogUtil.getPositionJudgeLog(busInstance);
		
		/* 不再待发区、存在上下行 */
		// "isdef LINE_TYPE && !isdef POSITION_PX"
		String str = "!isdef " + Constants.MSG_INFO_POSITION_PX;

		Serializable compiled = MVEL.compileExpression(str);
		Boolean result = (Boolean) MVEL.executeExpression(compiled, busInstance.getAttributes());
		if (result) {
			if (busInstance.isInStandBy()) {
				log.debug("第五步 偏线判断（在待发区 ）");
				busInstance.setAttributeDeviate(Constants.VAL_IS_PX_0);
			} else if (busInstance.isLineTypeExist()) {
//			} else if (busInstance.isInOperateTime() && busInstance.isLineTypeExist()) {
				
				log.debug("第五步 偏线判断（不再待发区、存在上下行 ）");
				
				if(isInDeviateplan(busInstance)){
					// 设置偏线状态为非偏线，结束偏线判定
					busInstance.setAttributeDeviate(Constants.VAL_IS_PX_0);
				}
				
				boolean isDeviate = busLineService.isDeviate(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getLatitude(), busInstance.getLongitude());
				if (isDeviate) {
					busInstance.setAttributeDeviate(Constants.VAL_IS_PX_1);

				} else {
					busInstance.setAttributeDeviate(Constants.VAL_IS_PX_0);
				}
			}
		}
		
		logger.debug("【偏线判断】偏线状态：{}", (busInstance.isInDeviate()? "偏线":"未偏线"));
	}

	
	/**
	 * 是否在偏线计划中
	 * @return
	 */
	private boolean isInDeviateplan(BusInstance busInstance){
		MultiLog log = MultiLogUtil.getPositionJudgeLog(busInstance);
		
		boolean flag = false;
		// 1、计划偏线，需要根据站点判定，所以放在站点之后
		// 注：这里目前主要使用在里程计算时候，如需要在直线条上偏线计划显示在直线图上，这里需要
		boolean isMileageCaculate = busInstance.isBusMileageCaculate();
		boolean deviateplan = PropertiesUtils.getBoolean("system.parameter.deviateplan", false);
//		if(deviateplan && !busInstance.isEnterOut()){		// 偏线计划中，在直线图上正常显示i
		if(deviateplan && !busInstance.isEnterOut() && isMileageCaculate){	// 偏线计划中，在里程计算中体现
			// 设置偏线计划，并且不是进出站上报
//			String stationSeq = busInstance.getStationSeq();
			// 没有进出站状态信息  从上一个点取站点信息（漂移数据已经过滤掉）
			
			TimingPoint prePoint = busInstance.getTimingPoint(-1);
			if(prePoint != null){
				if(!prePoint.containsAttribute(Constants.LINE_STATION_SEQ)){
					// 没有取前2个点的信息
					prePoint = busInstance.getTimingPoint(-2);
				}
			}
			String stationSeq = prePoint.getStationSeq();
			
			if(!PMSUtils.isEmpty(stationSeq)){
//				boolean isInDevatePlan = deviateService.isInDeviatePlan(lineUuid, lineType, busInstance.getTime(), Integer.parseInt(busInstance.getStationSeq()));
				boolean isInDevatePlan = deviateService.isInDeviatePlan(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getTime(), Integer.parseInt(stationSeq));
				
				// 在偏线计划中，直接返回数据未偏线
				if(isInDevatePlan){
					flag = true;
					log.debug("\t{} lineName:{}, lineType:{} 偏线计划中，设置为运营，非偏线", busInstance.getBusNumber(), busInstance.getLineUuid(), busInstance.getLineType());
				}
			}else{
				
			}
		}
		return flag;
	}

}
